<script setup>
import { ref, reactive, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app';
import { addNewCustomerApi, getCustomerApi } from '@/api/customer';
import { useUserStore } from '../../../store/user';
import { editCustomerApi } from '@/api/customer';
import ProvincePicker from '@/components/province-picker/index.vue';
import { useGlobalStore } from '@/store/global';

const userStore = useUserStore();
const globalStore = useGlobalStore();
const targetId = ref(-1);

// 表单数据
const formData = reactive({
  // 身份信息
  name: '',
  idType: 0,
  idNumber: '',
  // 其他信息
  gender: '男',
  phone: '',
  birthdate: new Date(),
  relationship: '本人',
  // 收货信息
  address: '',
  detailAddress: ''
})

// 省市县选择器相关
const showProvincePicker = ref(false)
const selectedRegion = ref({
  province: '',
  city: '',
  district: '',
  fullAddress: ''
})

onLoad(async (options) => {
  targetId.value = typeof options.id !== 'undefined' ? Number(options.id) : -1;
  if (targetId.value !== -1) {
    try {
      const results = await getCustomerApi({
        id: targetId.value
      });
      Object.assign(formData, {
        // 身份信息
        name: results.name,
        idType: results.certificatetype,
        idNumber: results.certificatenumber,
        // 其他信息
        gender: results.gender === 0 ? '男' : '女',
        phone: results.phonenumber,
        birthdate: new Date(results.birthdate),
        relationship: results.relationship,
        // 收货信息 - 解析JSON数组格式
        address: '',
        detailAddress: ''
      });
      
      // 解析地址数据
      try {
        const addressData = JSON.parse(results.reportdeliveryaddress);
        if (Array.isArray(addressData) && addressData.length >= 2) {
          formData.address = addressData[0] || '';
          formData.detailAddress = addressData[1] || '';
          
          // 初始化省市县数据
          selectedRegion.value = {
            province: '',
            city: '',
            district: '',
            fullAddress: formData.address
          };
        }
      } catch (error) {
        console.error('解析地址数据失败:', error);
        // 如果解析失败，尝试按旧格式处理
        const addressParts = results.reportdeliveryaddress.split(' ');
        if (addressParts.length >= 2) {
          formData.address = addressParts[0] || '';
          formData.detailAddress = addressParts[1] || '';
          
          selectedRegion.value = {
            province: '',
            city: '',
            district: '',
            fullAddress: formData.address
          };
        }
      }
    } catch (error) {
      console.error('getCustomer error', error);
      uni.showToast({
        title: '获取信息失败',
        icon: 'error'
      });
    }
  }
});

// 表单验证规则
const validateForm = () => {
  const errors = []

  // 姓名验证
  if (!formData.name.trim()) {
    errors.push('请输入姓名')
  } else if (!/^[\u4e00-\u9fa5]{2,4}$/.test(formData.name)) {
    errors.push('姓名请输入2-4个中文字符')
  }

  // 证件号验证（身份证）
  if (!formData.idNumber.trim()) {
    errors.push('请输入证件号码')
  }

  // 手机号验证
  if (!formData.phone.trim()) {
    errors.push('请输入手机号')
  } else if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
    errors.push('请输入正确的手机号')
  }

  // 收货地区验证
  if (!formData.address.trim()) {
    errors.push('请输入收货地区')
  }

  // 详细地址验证
  if (!formData.detailAddress.trim()) {
    errors.push('请输入详细地址')
  }

  return errors
}

// 选择器选项
const idTypeOptions = [
  {
    id: 0,
    name: '身份证'
  },
  {
    id: 1,
    name: '护照'
  }
]
const relationshipOptions = ['本人', '父亲', '母亲', '配偶', '子女', '其他']

// 计算属性：获取证件类型的显示名称
const idTypeName = computed(() => {
  const option = idTypeOptions.find(item => item.id === formData.idType)
  return option ? option.name : '身份证'
})

// 性别选择
const handleGenderChange = (e) => {
  formData.gender = e.detail.value
}

// 证件类型选择
const handleIdTypeSelect = () => {
  uni.showActionSheet({
    itemList: idTypeOptions.map(item => item.name),
    success: (res) => {
      const oldValue = formData.idType
      formData.idType = idTypeOptions[res.tapIndex].id
      console.log('证件类型更改:', {
        from: oldValue,
        to: formData.idType,
        name: idTypeOptions[res.tapIndex].name
      })
    }
  })
}

// 关系选择
const handleRelationshipSelect = () => {
  uni.showActionSheet({
    itemList: relationshipOptions,
    success: (res) => {
      formData.relationship = relationshipOptions[res.tapIndex]
    }
  })
}

// 生日选择
const handleBirthdateChange = (e) => {
  formData.birthdate = new Date(e.detail.value)
}

// 打开地区选择器
const openRegionPicker = () => {
  showProvincePicker.value = true
}

// 确认地区选择
const handleRegionConfirm = (result) => {
  selectedRegion.value = result
  formData.address = result.fullAddress
  uni.showToast({
    title: '地区选择成功',
    icon: 'success',
    duration: 1000
  })
}

// 取消地区选择
const handleRegionCancel = () => {
  console.log('取消选择地区')
}

// 保存表单
const handleSave = async () => {
  const errors = validateForm()

  if (errors.length > 0) {
    uni.showToast({
      title: errors[0],
      icon: 'none',
      duration: 2000
    })
    return
  }

  // 表单验证通过，提交数据
  try {
    uni.showLoading({
      title: '保存中...'
    })

    console.log('准备保存的数据:', {
      certificatetype: formData.idType,
      name: formData.name,
      certificatenumber: formData.idNumber
    })

    if (targetId.value !== -1) {
      const editData = {
        id: targetId.value,
        name: formData.name,
        certificatetype: formData.idType,
        certificatenumber: formData.idNumber,
        gender: formData.gender === '男' ? 0 : 1,
        birthdate: formData.birthdate,
        relationship: formData.relationship,
        reportdeliveryaddress: JSON.stringify([formData.address, formData.detailAddress]),
        phonenumber: formData.phone
      }
      console.log('调用editCustomerApi，数据:', editData)
      await editCustomerApi(editData)
    } else {
      const addData = {
        uid: userStore.userInfo.id,
        name: formData.name,
        certificatetype: formData.idType,
        certificatenumber: formData.idNumber,
        gender: formData.gender === '男' ? 0 : 1,
        birthdate: formData.birthdate,
        relationship: formData.relationship,
        reportdeliveryaddress: JSON.stringify([formData.address, formData.detailAddress]),
        phonenumber: formData.phone
      }
      console.log('调用addNewCustomerApi，数据:', addData)
      await addNewCustomerApi(addData);
    }
    
    uni.hideLoading()
    uni.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 1000
    });
    setTimeout(() => {
      uni.navigateBack(-1);
    }, 1000);
  } catch (error) {
    uni.hideLoading()
    console.error('handleSave error', error);
    uni.showToast({
      title: '保存失败',
      icon: 'error'
    });
  }
}
</script>

<template>
  <view class="app-edit">
    <view class="edit-form">
      <view class="form-title">
        <text>*</text>
        <text>身份信息</text>
      </view>
      <view class="form-content">
        <view class="form-input">
          <text>姓名</text>
          <input type="text" placeholder="需与证件姓名一致" v-model="formData.name" />
        </view>
        <view class="form-select" @click="handleIdTypeSelect">
          <text>证件类型</text>
          <view class="select-right">
            <text>{{ idTypeName }}</text>
            <uni-icons type="bottom" size="20" color="#3333332e"></uni-icons>
          </view>
        </view>
        <view class="form-input">
          <text>证件号</text>
          <input type="text" placeholder="请输入证件号码" v-model="formData.idNumber" />
        </view>
      </view>
    </view>

    <view class="edit-form">
      <view class="form-title">
        <text>*</text>
        <text>其他信息</text>
      </view>
      <view class="form-content">
        <view class="form-radio">
          <text>性别</text>
          <radio-group @change="handleGenderChange">
            <label>
              <radio :checked="formData.gender === '男'" value="男" color="#FF7F36" />
              男
            </label>
            <label>
              <radio :checked="formData.gender === '女'" value="女" color="#FF7F36" />
              女
            </label>
          </radio-group>
        </view>
        <view class="form-input">
          <text>手机号</text>
          <input type="number" placeholder="请输入手机号" v-model="formData.phone" />
        </view>
        <view class="form-picker">
          <text>生日</text>
          <picker mode="date" :value="formData.birthdate ? formData.birthdate.toISOString().split('T')[0] : ''"
            @change="handleBirthdateChange">
            <view class="picker-content">
              <text class="picker-text">
                {{ formData.birthdate ? formData.birthdate.toLocaleDateString('zh-CN') : '请选择生日' }}
              </text>
              <uni-icons type="bottom" size="20" color="#3333332e"></uni-icons>
            </view>
          </picker>
        </view>
        <view class="form-select" @click="handleRelationshipSelect">
          <text>与本人关系</text>
          <view class="select-right">
            <text>{{ formData.relationship }}</text>
            <uni-icons type="bottom" size="20" color="#3333332e"></uni-icons>
          </view>
        </view>
      </view>
    </view>

    <view class="edit-form">
      <view class="form-title">
        <text>*</text>
        <text>收货信息</text>
      </view>
      <view class="form-content">
        <view class="form-select" @click="openRegionPicker">
          <text>收货地区</text>
          <view class="select-right">
            <text class="address-text">{{ formData.address || '请选择省市县' }}</text>
            <uni-icons type="bottom" size="20" color="#3333332e"></uni-icons>
          </view>
        </view>

        <view class="form-input">
          <text>详细地址</text>
          <input type="text" placeholder="请输入详细地址" v-model="formData.detailAddress" />
        </view>
      </view>
    </view>

    <view class="save-button" @click="handleSave">
      <text>保存</text>
    </view>

    <!-- 省市县选择器 -->
    <ProvincePicker 
      v-model="selectedRegion"
      :show="showProvincePicker"
      :province-data="globalStore.provinceData"
      @update:show="showProvincePicker = $event"
      @confirm="handleRegionConfirm"
      @cancel="handleRegionCancel"
    />
  </view>
</template>

<style src="./style.scss" scoped />
